<template>
  <div>
    <el-upload class="upload-file" v-model="previewImgList" :before-read="beforeRead" :after-read="afterRead"
      :before-delete="beforeDelete" :multiple="limit > 1 && multiple" :accept="accept" :max-count="limit"
      @oversize="onOversize" upload-icon="plus"></el-upload>
    <div class="tip">
      提示：仅允许上传{{ accept }}格式文件
    </div>
  </div>
</template>

<script>
import { uploadFile } from "@/api/airport/inspect/index";
import { getFileTypeOther, isJSON } from "@/utils/index";
import ImageCompressor from 'image-compressor.js'

export default {
  props: {
    fileStr: {
      require: true,
    },
    limit: {
      type: Number,
      default: 1,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    accept: {
      type: String,
      default: ".jpge,.jpg,.png",
    },
  },
  emits: ["update:fileStr"],
  computed: {
    realFileList () {
      return this.storeList.filter((item) => {
        if (item && item.path && item.status !== "remove") {
          return true;
        }
      });
    },
  },
  watch: {
    fileStr: {
      immediate: true,
      handler (val) {
        if (val && isJSON(val)) {
          //如果前后不一致，说明是外部主动修改的数据，则重新加载数据
          if (val !== JSON.stringify(this.realFileList)) {
            this.storeList = JSON.parse(val);
            this.previewImgList = this.storeList.map((item) => {
              return {
                ...item,
                url: this.minioPath + item.path,
              };
            });
          }
        } else {
          this.previewImgList = [];
          this.storeList = [];
        }
      },
    },
    realFileList: {
      deep: true,
      handler (val) {
        this.$emit("update:fileStr", JSON.stringify(val));
      },
    },
  },
  data () {
    return {
      storeList: [],
      previewImgList: [],
      imgUrl: '',
    };
  },

  methods: {

    beforeRead (files, { index }) {
      //预插入数据
      if (files instanceof Array) {
        let remain = this.limit - this.previewImgList.length; //剩余可上传数量
        if (files.length > remain) {
          this.$showFailToast("超出可上传文件数量，请重新选择！");
          return false;
        } else {
          this.storeList.splice(index, 0, ...files);
        }
      } else {
        this.storeList.splice(index, 0, files);
      }
      return true;
    },
    afterRead (files, { index }) {
      this.imgUrl = files.file
      if (files instanceof Array) {
        for (let i = 0; i < files.length; i++) {
          this.handleUpload(files[i], index + i);
        }
      } else {
        this.handleUpload(files, index);
      }
    },
    async handleUpload (params, index) {
      // 图片压缩处理
      let file1 = await this.compressFile(this.imgUrl)
      let file2  = this.blobToFile(file1)
      return new Promise((resolve, reject) => {
        let file = file2;
        let previewImg = this.previewImgList[index];
        previewImg.status = "uploading";
        previewImg.message = "上传中...";
        uploadFile(file, getFileTypeOther(file.name), (progressEvent) => {
          //原生获取上传进度的事件
          if (progressEvent.lengthComputable) {
            //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
            //如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
            //
            let present = (
              (progressEvent.loaded / progressEvent.total) *
              100
            ).toFixed(2);
            previewImg.message = present + "%";
          }
        })
          .then((res) => {
           
            previewImg.status = "";
            previewImg.message = "";
            this.storeList[index] = res.data;
            this.storeList[index].status = "";
            this.storeList = [...this.storeList];
            resolve(res.data);
          })
          .catch((e) => {
            previewImg.status = "failed";
            previewImg.message = "上传失败";
            reject();
          });
      });
    },
    beforeDelete (file, { index }) {
      this.previewImgList[index].status = "remove";
      this.storeList[index].status = "remove";
      return true;
    },
    onOversize (file) {
      this.$showFailToast("文件大小不能超过 100MB");
    },
    compressFile (file) {
      return new Promise((resolve, reject) => {
        new ImageCompressor(file, {
          quality: 0.1, //压缩质量
          checkOrientation: false, //图片翻转，默认为false
          success (result) {
            resolve(result);
          },
          error (e) {
            reject(e)
          }
        })
      })
    },
    blobToFile(theBlob){
      theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
      theBlob.name = theBlob.name;                // 文件名
      return new File([theBlob], theBlob.name, {type: theBlob.type, lastModified: Date.now()});
    },
  }
}
</script>
<style lang="scss" scoped>
.tip {
  line-height: 1.5;
  color: #666;
  font-size: 12px;
  margin-bottom: 10px;
}
</style>
